﻿using android_charge.Utils;
using Bogus;
using log4net.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static System.Windows.Forms.LinkLabel;


namespace android_charge.compent
{
    public partial class Content : UserControl
    {
        public object[] Items = new object[] { "谷歌账号", "谷歌密码", "辅助邮箱", "卡号", "过期时间", "卡密码", "zip", "亚马逊账号", "亚马逊密码", "谷歌密码" };

        public int flagIndex = 7;

        public bool isUK = false;

        public string lastAmazonAcc = "";

        public List<JObject> accounts = new List<JObject>();

        public JObject currAccount = new JObject();

        public int chargeIndex = 0;

        public Faker<Add> addressFaker = new Faker<Add>()
            .RuleFor(a => a.Street, f => f.Address.StreetAddress())
            .RuleFor(a => a.Country, f => "United States");

        public static HttpClient client = new HttpClient(new HttpClientHandler
        {
            Proxy = null,
            UseProxy = false
        });

        public Content()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(Items);

        }

        public void setItems(Object[] Items)
        {
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(Items);
        }

        private void next_Click(object sender, EventArgs e)
        {
            if (this.Parent is Amazon tool)
            {
                chargeIndex = 0;
                if (info.Text == "" && accounts.Count() == 0)
                {
                    return;
                }
                else
                {
                    // 下一个
                    if (info.Text != "")
                    {
                        // 第一次点击 初始化accounts
                        accounts.Clear();
                        var datas = info.Text.Split('\r');
                        foreach (var item in datas)
                        {
                            var obj = new JObject();
                            var info = item.Split('\t');
                            obj.Add("gAccount", info[0].Trim());
                            obj.Add("gPassword", info[1].Trim());
                            obj.Add("fuEmail", info[2].Trim());
                            if (info.Length >= 4)
                            {
                                var cardInfo = info[3].Split('|');
                                obj.Add("number", cardInfo[0].Trim());
                                obj.Add("exDate", cardInfo[1].Replace("/", ""));
                                obj.Add("pwd", cardInfo[2].Trim());
                            }
                            if (info.Length >= 5)
                            {
                                tool.link = info[4];
                            }
                            accounts.Add(obj);
                        }
                        // 初始化完 清空text
                        info.Text = "";
                    }
                    // 获取并移除第一个
                    setcurrAccount(accounts.First());
                    accounts.RemoveAt(0);
                }

            }


        }

        private void info_click(object sender, EventArgs e)
        {
            if (sender is Label label)
            {
                Clipboard.SetText(label.Text);
            }
        }

        private void indexInput_Click(object sender, EventArgs e)
        {
            if (this.Parent is Amazon tool)
            {
                if (comboBox1.SelectedIndex == 0 || comboBox1.SelectedIndex == flagIndex)
                {
                    //输入的是谷歌账号或亚马逊账号 开启全局
                    Task.Run(() =>
                    {
                        tool.switchClashMode(ClashMode.GLOBAL);
                    });
                }
                tool.Send(getCurrValueAndNext());

            }


        }

        public string getByName(string name)
        {
            if (currAccount != null && currAccount[name] != null)
            {
                return currAccount[name].ToString();
            }
            return "";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            currInfo.Text = getCurrValue();
        }
        private void changeIndex(int index)
        {
            comboBox1.SelectedIndex = index;
            comboBox1_SelectedIndexChanged(null, null);
        }

        public string getCurrValue()
        {
            if (this.Parent is Amazon tool)
            {
                // var currAccount = tool.currAccount;
                var labelMap = tool.labelMap;
                if (currAccount != null && currAccount[labelMap[comboBox1.SelectedIndex]] != null)
                {
                    return currAccount[labelMap[comboBox1.SelectedIndex]].ToString();
                }
            }
            return "";
        }

        public string getCurrValueAndNext()
        {
            if (this.Parent is Amazon tool)
            {
                var labelMap = tool.labelMap;
                try
                {
                    if (currAccount != null && currAccount[labelMap[comboBox1.SelectedIndex]] != null)
                    {
                        var count = labelMap.Length - 1;
                        if (comboBox1.SelectedIndex != labelMap.Length - 1)
                        {
                            count = comboBox1.SelectedIndex++;
                            comboBox1_SelectedIndexChanged(null, null);
                        }
                        return currAccount[labelMap[count]].ToString();
                    }
                }
                catch
                {

                }

            }
            return "";

        }

        private void cardInput_Click(object sender, EventArgs e)
        {
            if (this.Parent is Amazon tool)
            {
                if (!isUK)
                {
                    Task.Run(() =>
                    {
                        tool.batch_adb_input(
                            getByName("number"), getByName("exDate"), getByName("pwd"), 2, tool.zip
                        );

                    });
                }
                else
                {
                    // 英国有两种
                    Task.Run(() =>
                    {
                        tool.batch_adb_input(
                            getByName("number"), getByName("exDate"), getByName("pwd"), 2, getByName("sta"), 2, getByName("pt"),
                            1, getByName("pc")
                        );

                    });
                }


                changeIndex(flagIndex);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            amzonAccount(null, null);
        }

        public async void amzonAccount(object sender, EventArgs e)
        {
            string link = "54117";
            if (this.Parent is Amazon_JP_NEW tool)
            {
                link = tool.link;
            }
            if (sender != null)
            {
                // 是换账号 不是第一次拿账号 上一个账号标记禁用
                amazonStatus(3, link);
            }
            else
            {
                amazonStatus(1, link);
            }
            try
            {
                var url = $"http://hy.51wmsy.com/api/get_amazon_account_cs?phone_type=1&country=us&operator=%E5%B8%B8%E5%B1%B1API%E7%94%A8%E6%88%B7&camp_id=54117";
                if (this.Parent is Amazon_JP_NEW)
                {
                    url = $"http://hy.51wmsy.com/api/get_amazon_account_cs?phone_type=1&country=jp&operator=%E5%B8%B8%E5%B1%B1API%E7%94%A8%E6%88%B7&camp_id={link}";
                }

                var res = await client.GetStringAsync(url);
                var obj = JsonConvert.DeserializeObject<JObject>(res);
                if (obj["status"].ToString().Equals("1"))
                {
                    currAccount["amzonAcc"] = obj["data"]["account_name"];
                    currAccount["amPwd"] = obj["data"]["password"];
                    lastAmazonAcc = currAccount["amzonAcc"].ToString();
                    if (isUK)
                    {
                        UKAdd.Random(currAccount);
                    }
                    changeIndex(flagIndex);
                }
                else
                {
                    MessageBox.Show(res);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public async void amazonStatus(int status, string cmp = "54117")
        {
            if (!string.IsNullOrEmpty(lastAmazonAcc))
            {
                try
                {
                    await client.GetAsync($"http://hy.51wmsy.com/api/return_get_amazon_account_cs?camp_id={cmp}&email={lastAmazonAcc}&use_status={status}");
                }
                catch (Exception ex)
                {
                }

            }
        }
        public void setcurrAccount(JObject account, string cuLink = "")
        {
            if (this.Parent is Amazon tool)
            {
                currAccount = account;
                changeIndex(0);
                if (!string.IsNullOrEmpty(cuLink))
                {
                    tool.link = cuLink;
                }
                if (isUK)
                {
                    UKAdd.Random(currAccount);
                }
            }

        }

        private void Content_Load(object sender, EventArgs e)
        {
            if (this.Parent is Amazon_UK_NEW tool)
            {
                flagIndex = 9;
                isUK = true;
            }
        }

        private void e5_Click(object sender, EventArgs e)
        {
            if (this.Parent is Amazon_UK_NEW uk)
            {

                // 刷新英国地址
                UKAdd.Random(currAccount);
                Task.Run(() =>
                {
                    uk.batch_adb_input(
                        6, getByName("pc"), 1, getByName("sta"), 2, getByName("pt"), 5
                    );
                });
            }
            else if (this.Parent is Amazon_US_NEW us)
            {
                var add = addressFaker.Generate();
                Task.Run(() =>
                {
                    us.batch_adb_input(
                        6, add.Street, 2, getByName("city"), 2, getByName("zip"), 5
                    );
                });

            }

        }

        private void export_Click(object sender, EventArgs e)
        {
            Clipboard.SetText($"{currAccount["amzonAcc"]}\t{currAccount["amPwd"]}");
        }
    }
    public class Add
    {
        public string Street { get; set; }
        public string Country { get; set; }
    }
}
